package cn.bugstack.mybatis.type;

import cn.bugstack.mybatis.datasource.druid.DruidDatasourceFactory;
import cn.bugstack.mybatis.io.Resources;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * 类型别名注册表
 */
public class TypeAliasRegistry {

    private final Map<String,Class<?>> TYPE_ALIASES = new HashMap<>();


    public TypeAliasRegistry() {
        registerAlias("string", String.class);
        registerAlias("int", Integer.class);
        registerAlias("DRUID", DruidDatasourceFactory.class);
    }

    public void registerAlias(String alias, Class<?> type) {
        String key = alias.toLowerCase(Locale.ENGLISH);
        TYPE_ALIASES.put(key, type);
    }

    public Class<?> resolveAlias(String alias) throws ClassNotFoundException {
        if (alias == null) {
            return null;
        }

        String key = alias.toLowerCase(Locale.ENGLISH);


        Class<?> value;
        if (TYPE_ALIASES.containsKey(key)) {
            value = TYPE_ALIASES.get(key);
        } else {
            value = Resources.classForName(alias);
        }
        return value;
    }
}
